package com.yeeverse.sdk.api;

import com.yeeverse.sdk.exception.SdkException;
import com.yeeverse.sdk.util.PropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description:
 * @Author: kai.yang
 * @Date: 2020-12-30 11:30
 */
public class SdkContextBuilder {

    private static final Logger logger = LoggerFactory.getLogger(SdkContextBuilder.class);

    private static PropertiesUtils propertiesUtils;

    static {
        try {
            propertiesUtils = PropertiesUtils.getInstance("paycenter");
        } catch (Exception e) {
            logger.info("未自定义初始化sdk配置文件");
        }
    }

    /**
     * 应用id
     */
    private String appId;
    /**
     * 商户私钥
     */
    private String privateKey;
    /**
     * yeeverse公钥
     */
    private String publictKey;
    /**
     * yeeverse基础路径
     */
    private String baseUrl;

    private final AtomicBoolean needSet = new AtomicBoolean(false);

    public SdkContextBuilder() {
    }

    public SdkContextBuilder(String appId, String privateKey, String publictKey, String baseUrl) {
        if (needSet.compareAndSet(false, true)) {
            this.appId = appId;
            this.privateKey = privateKey;
            this.publictKey = publictKey;
            this.baseUrl = baseUrl;
        } else {
            logger.warn("不能重复初始化环境变量");
        }
    }

    public SdkContext initContext() {
        return build();
    }

    public SdkContext initContext(String env) {
        propertiesUtils = PropertiesUtils.getInstance(env + "_paycenter");
        this.needSet.compareAndSet(true, false);
        return build();
    }

    /**
     * 构建配置参数
     *
     * @return sdk配置
     */
    private SdkContext build() {
        if (needSet.get()) {
            return new SdkContext(this.appId, this.privateKey, this.publictKey, this.baseUrl);
        } else {
            try {
                this.appId = propertiesUtils.getProperty("appId");
                this.privateKey = propertiesUtils.getProperty("privateKey");
                this.publictKey = propertiesUtils.getProperty("publicKey");
                this.baseUrl = propertiesUtils.getProperty("baseUrl");
            } catch (Exception e) {
                logger.warn("初始化SDK报错", e);
                throw new SdkException("sdk环境变量未初始化，可以选择build或配置文件的方式");
            }
            return new SdkContext(this.appId, this.privateKey, this.publictKey, this.baseUrl);
        }
    }
}
